#include "descr/descr_settlement_mechanics_parser.h"

#include "TinyXML/tinyxml.h"
#include "settlement_type.h"


using namespace std;


bool DescrSettlementMechanicsParser::open(string filepath)
{
	TiXmlDocument doc(filepath.c_str());

	if (doc.LoadFile())
	{
		TiXmlElement* root = doc.RootElement();

		for (TiXmlElement* section = root->FirstChildElement(); section != NULL; section = section->NextSiblingElement())
		{
			string sectionName = section->Value();
			if (sectionName.compare("population_levels") == 0)
			{
				bool isCastle = false;
				for (TiXmlNode* node = section->FirstChild(); node != NULL; node = node->NextSibling())
				{
					string nodeValue = node->Value();
					if (node->Type() == TiXmlNode::TINYXML_COMMENT)
					{
						nodeValue.erase(0, nodeValue.find_first_not_of(" \t"));
						nodeValue.erase(nodeValue.find_last_not_of(" \t") + 1);

						if (nodeValue.compare("city") == 0)
						{
							isCastle = false;
						}
						if (nodeValue.compare("castle") == 0)
						{
							isCastle = true;
						}
					}

					if (node->Type() == TiXmlNode::TINYXML_ELEMENT)
					{
						TiXmlElement* element = node->ToElement();
						string name = element->Attribute("name");

						shared_ptr<SettlementType> settlementType(new SettlementType());
						settlementType->id = name;
						settlementType->isCastle = isCastle;
						SettlementType::add(settlementType);
					}
				}
			}
		}
	}

	return true;
}